<script lang="ts" setup>
import type {
  AnalysisOverviewItem,
  WorkbenchProjectItem,
  WorkbenchQuickNavItem,
} from '@vben/common-ui';
import type { TabOption } from '@vben/types';

import { markRaw, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  AnalysisChartCard,
  AnalysisChartsTabs,
  AnalysisOverview,
  WorkbenchHeader,
  WorkbenchQuickNav,
} from '@vben/common-ui';
import { SvgBellIcon, SvgCakeIcon, SvgCardIcon } from '@vben/icons';
import { preferences } from '@vben/preferences';
import { useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';

import { client } from '#/api/core/client';

import AnalyticsTrends from './analytics-trends.vue';
import AnalyticsVisitsData from './analytics-visits-data.vue';
import AnalyticsVisits from './analytics-visits.vue';

interface StatTypeSummary {
  today: number;
  total: number;
}

interface StatOverviewResponse {
  upload: StatTypeSummary;
  download: StatTypeSummary;
  visit: StatTypeSummary;
}

interface TrendPoint {
  x: string;
  y: number;
}

const userStore = useUserStore();
const quickNavItems: WorkbenchQuickNavItem[] = [
  {
    color: '#1fdaca',
    icon: 'ion:home-outline',
    title: '首页',
    url: '/file',
  },
  {
    color: '#bf0c2c',
    icon: 'ion:download-outline',
    title: '下载',
    url: '/download',
  },
  {
    color: '#e18525',
    icon: 'ion:cloud-upload-outline',
    title: '上传',
    url: '/upload',
  },
  {
    color: '#3fb27f',
    icon: 'ion:share-outline',
    title: '分享',
    url: '/share',
  },
  {
    color: '#a0a0a0',
    icon: 'ion:layers-outline',
    title: '组件',
    url: '/FluntUI',
  },
  {
    color: '#3f51b5',
    icon: 'ion:help-circle-outline',
    title: '关于',
    url: '/about',
  },
];
const router = useRouter();

function navTo(nav: WorkbenchProjectItem | WorkbenchQuickNavItem) {
  if (nav.url?.startsWith('http')) {
    openWindow(nav.url);
    return;
  }
  if (nav.url?.startsWith('/')) {
    router.push(nav.url).catch((error) => {
      console.error('Navigation failed:', error);
    });
  } else {
    console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
  }
}
const trafficTrend = ref<TrendPoint[]>([]);
const visitTrend = ref<TrendPoint[]>([]);
const overviewItems = ref<AnalysisOverviewItem[]>([]);

function getCurrentMonthDateRange(): { endDate: string; startDate: string } {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();
  const startDate = new Date(year, month, 1);
  const endDate = new Date(year, month + 1, 0);
  function formatDate(date: Date) {
    return date.toISOString().slice(0, 10);
  }
  return { startDate: formatDate(startDate), endDate: formatDate(endDate) };
}
function getTotalUpload(data: StatOverviewResponse) {
  return data.upload.total;
}

async function loadTrafficTrend(startDate: string, endDate: string) {
  const [visitRes, uploadRes, downloadRes] = await Promise.all([
    client.stat.getRangeStats('visit', startDate, endDate),
    client.stat.getRangeStats('upload', startDate, endDate),
    client.stat.getRangeStats('download', startDate, endDate),
  ]);
  const visits = visitRes.data;
  const uploads = uploadRes.data;
  const downloads = downloadRes.data;

  const dates = new Set([
    ...Object.keys(downloads),
    ...Object.keys(uploads),
    ...Object.keys(visits),
  ]);

  trafficTrend.value = [...dates].sort().map((date) => ({
    x: date,
    y: (visits[date] || 0) + (uploads[date] || 0) + (downloads[date] || 0),
  }));
}

async function loadVisitTrend(startDate: string, endDate: string) {
  const visitRes = await client.stat.getRangeStats('visit', startDate, endDate);
  const visits = visitRes.data;

  visitTrend.value = Object.entries(visits).map(([date, value]) => ({
    x: date,
    y: value,
  }));
}

async function loadOverview() {
  try {
    const response = await client.stat.getAllTypeStats();
    const data = response.data as unknown as StatOverviewResponse;

    overviewItems.value = [
      {
        icon: markRaw(SvgCakeIcon), // ✅ 使用 markRaw
        title: '访问量',
        totalTitle: '总访问量',
        totalValue: data.visit.total,
        value: data.visit.today,
      },
      {
        icon: markRaw(SvgBellIcon), // ✅ 使用 markRaw
        title: '使用量',
        totalTitle: '总使用量',
        totalValue: data.download.total + data.upload.total,
        value: data.download.today + data.upload.today,
      },
      {
        icon: markRaw(SvgCardIcon), // ✅ 使用 markRaw
        title: '上传量',
        totalTitle: '总上传量',
        totalValue: getTotalUpload(data),
        value: data.upload.today,
      },
    ];
  } catch (error) {
    console.error('获取统计数据失败', error);
  }
}
const chartTabs: TabOption[] = [
  {
    label: '流量趋势',
    value: 'trends',
  },
  {
    label: '日访问量',
    value: 'visits',
  },
];
onMounted(async () => {
  const { startDate, endDate } = getCurrentMonthDateRange();

  await Promise.all([
    loadTrafficTrend(startDate, endDate),
    loadVisitTrend(startDate, endDate),
    loadOverview(),
  ]);
});
</script>

<template>
  <div class="p-5">
    <WorkbenchHeader
      :avatar="userStore.userInfo?.avatar || preferences.app.defaultAvatar"
    >
      <template #title>
        Hello, {{ userStore.userInfo?.realName }}, 欢迎回来！
      </template>
      <template #description> 今日晴，20℃ - 32℃！ </template>
    </WorkbenchHeader>

    <!-- 第二行：快捷导航 + 数据概览 -->
    <div class="mt-5 flex flex-col gap-5 xl:flex-row">
      <!-- 快捷导航 -->
      <div class="w-full xl:w-2/5">
        <WorkbenchQuickNav
          :items="quickNavItems"
          title="快捷导航"
          @click="navTo"
        />
      </div>

      <div class="w-full xl:w-3/5">
        <AnalysisOverview :items="overviewItems" />
      </div>
    </div>

    <div class="mt-5 flex flex-col gap-5 xl:flex-row">
      <AnalysisChartsTabs :tabs="chartTabs" class="w-full xl:w-3/5">
        <template #trends>
          <AnalyticsTrends :data="trafficTrend" />
        </template>
        <template #visits>
          <AnalyticsVisits :data="visitTrend" />
        </template>
      </AnalysisChartsTabs>
      <AnalysisChartCard title="访问数量" class="w-full xl:w-2/5">
        <AnalyticsVisitsData />
      </AnalysisChartCard>
    </div>
  </div>
</template>
